import os
import psycopg2
import json
import datetime
import time
import yaml
from redis import StrictRedis,ConnectionPool



class DB_handler(object):

    def __init__(self,config):
        super(DB_handler,self).__init__()
        self.config=config
        self.connect= psycopg2.connect(database=self.config['postgres']['database'], user=self.config['postgres']['user'], password=self.config['postgres']['password'],
                                        host=self.config['postgres']['host'],port=self.config['postgres']['port'])
        self.cur=self.connect.cursor()

        self.pool=ConnectionPool(host=config['redis']['host'],port=config['redis']['port'],db=config['redis']['db'])
        self.rs=StrictRedis(connection_pool=self.pool)

    def connect_post(self):
        self.connect= psycopg2.connect(database=self.config['postgres']['database'], user=self.config['postgres']['user'], password=self.config['postgres']['password'],
                                        host=self.config['postgres']['host'],port=self.config['postgres']['port'])
        self.cur=self.connect.cursor()

    def close_all(self):
        """
        关闭所有连接
        :return:
        """
        self.connect.close()

    def qsave(self,data):
        if data:
            sql=f"insert into query_set.q(out_id,module,asker,content,answer,ha_answer,label,ask_time)" \
                f" values ('{data['out_id']}','{data['module']}','{data['asker']}','{data['content']}','{data['answer']}'" \
                f",'{data['ha_answer']}','{data['label']}','{data['ask_time']}')"
            try:
                self.cur.execute(sql)
                self.connect.commit()
                print('写入成功')
            except Exception as qsave_ERR:
                print(str(qsave_ERR))

    def rs_qsave(self,data_list):
        """
        从redis数据库里写入内容
        :param data_list:
        :return:
        """
        Done=False
        if data_list:
            try:
                for data in data_list:
                    sql = "update query_set.q set out_id ='{}',module='{}',asker='{}', content='{}',answer='{}',ha_answer='{}',label='{}'," \
                          "ask_time='{}'".format(data['out_id'], data['module'], data['asker'], data['content'],
                                                 data['answer'],
                                                 data['label'], data['ask_time'])

                    self.cur.execute(sql)
                self.connect.commit()
                Done=True
            except Exception as rs_qsave_ERR:
                    print(str(rs_qsave_ERR))
        return Done


class HA_Server(object):

    def __init__(self):
        super(HA_Server, self).__init__()

        self.config=self.init_config()
        self.db_handler=DB_handler(self.config)

    def init_config(self):
        file_data = ''
        CONF_PATH = os.path.join(os.path.dirname(__file__), 'conf', 'conf.yaml')
        with open(CONF_PATH, 'r', encoding='utf8') as r:
            file_data = r.read()

        config = yaml.load(file_data, Loader=yaml.FullLoader)
        return config

    def listening(self):
        while True:
            pass

    def test_qsave(self,data):
        self.db_handler.qsave(data)
        self.db_handler.close_all()

if __name__ == '__main__':
    has=HA_Server()
    current_time=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    data={'out_id':'','module':'SOP','asker':'老张','content':'什么是houdini python state','answer':'管理otl','ha_answer':'这个我不知道','label':'','ask_time':current_time}
    has.test_qsave(data)